package cn.edu.zafu.bigdata.YinMingyan.chapter07;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class FileAppendAndRead {

    public static void appendToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
            writer.write(content);
            writer.newLine(); // 添加一个新行，以便下一次追加时内容不会紧挨着上一次的内容
            System.out.println("内容追加成功！");
        } catch (IOException e) {
            System.out.println("追加内容到文件时发生错误: " + e.getMessage());
        }
    }

    public static void readFile(String fileName) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(fileName));
            System.out.println("文件内容如下：");
            System.out.println(new String(bytes));
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要追加的文本内容: ");
        String inputText = scanner.nextLine();

        String fileName = "files/202211080105.txt"; // 确保这个路径是正确的，并且有权限写入
        appendToFile(fileName, inputText);

        readFile(fileName);

        scanner.close();
    }
}
